package com.hdlang.android.v2.patch.plugin;

import com.hdlang.android.v2.patch.ChangeQuickRedirect;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

public class RobustClassVisitor extends ClassVisitor {
    private String className;

    public RobustClassVisitor(int api, ClassVisitor classVisitor) {
        super(api, classVisitor);
        visitField(
                Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "changeQuickRedirect",
                Type.getDescriptor(ChangeQuickRedirect.class), null, null
        );
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces);
        this.className = name;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = super.visitMethod(access, name, descriptor, signature, exceptions);
        final boolean isAbstractMethod = (access & Opcodes.ACC_ABSTRACT) != 0;
        final boolean isNativeMethod = (access & Opcodes.ACC_NATIVE) != 0;
        if (isAbstractMethod || isNativeMethod) {
            return methodVisitor;
        } else {
            return new RobustMethodAdapter(this.className, api, methodVisitor, access, name, descriptor);
        }
    }

}
